//
//  ViewController.m
//  DownLoadByNSURLSession
//
//  Created by @Zs on 16/4/17.
//  Copyright © 2016年 @Zs. All rights reserved.
//

#import "ViewController.h"
#import "MBProgressHUD+MJ.h"

@interface ViewController ()<NSURLSessionDownloadDelegate>
{
     NSURLSessionDownloadTask *_downloadTask;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
}


/**
 *  通过NSURLSession 请求数据
 */
-(void)loadDownNetJson{

    //1.创建URL
    NSURL *url = [NSURL URLWithString:@"http://graph.luoo.net/index/random?key=86aef0c62be013159025911a8c79ced1&platform=ios"];
    
    //2.创建请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //3.创建会话(这里使用一个全局会话),并且启动任务
    NSURLSession *session = [NSURLSession sharedSession];
    //从会话创建任务
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (!error) {
//            NSString *dataStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"数据请求成功");
        }else{
        
            NSLog(@"error is :%@",error.localizedDescription);
        }
    }];
    
    [dataTask resume];//恢复线程,启动任务
    
}
- (IBAction)down1:(id)sender {

    [self downloadFileByConfiguration:@"http://luoo-mp3.kssws.ks-cdn.com/low/chinese/20160109.mp3" fileName:@"test1.mp3"];
    [MBProgressHUD showSuccess:@"开始下载任务1"];
}

- (IBAction)down2:(id)sender {
    
    [self downloadFileByConfiguration:@"http://luoo-mp3.kssws.ks-cdn.com/low/they/20140228.mp3" fileName:@"test2.mp3"];
    [MBProgressHUD showSuccess:@"开始下载任务2"];
}


/**
 *  普通下载
 *
 *  @param downUrl  url
 *  @param fileName 文件名
 */
-(void)downloadFile:(NSString *)downUrl fileName:(NSString *)fileName{
    //1.创建url
    NSURL *url = [NSURL URLWithString:downUrl];
    //2.创建请求
    NSMutableURLRequest *request  = [NSMutableURLRequest requestWithURL:url];
    //3.创建会话
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
        if (!error) {
            NSError *saveError;
            NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
            NSString *savePath = [cachePath stringByAppendingPathComponent:fileName];
            NSLog(@"savePath --->%@",savePath);
            NSURL *saveUrl = [NSURL fileURLWithPath:savePath];
            [[NSFileManager defaultManager]copyItemAtURL:location toURL:saveUrl error:&saveError];
            if (!saveUrl) {
                NSLog(@"save success");
            }else{
            
                NSLog(@"error is :%@",saveError.localizedDescription);
            }
            
        }else{
            NSLog(@"error is :%@",error.localizedDescription);
        }
        
    }];
    
    [downloadTask resume];
    
}

/**
 *  通过NSURLSessionConfiguration,配置下载,有代理方法,支持监听下载进度,自动网络选择,后台下载,文件下载完毕之后位移
 *
 *  @param downUrl  url
 *  @param fileName 保存文件名
 */
-(void)downloadFileByConfiguration:(NSString *)downUrl fileName:(NSString *)fileName{
    //1.创建url
    NSURL *url = [NSURL URLWithString:downUrl];
    //2.创建请求
    NSMutableURLRequest *request  = [NSMutableURLRequest requestWithURL:url];
    //3.创建会话
    NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    sessionConfig.timeoutIntervalForRequest = 5.0f;//请求超时时间
    sessionConfig.allowsCellularAccess = true;//是否允许蜂窝网络下载(2G/3G/4G)
    NSURLSession *session  = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];//指定配置和代理
    
    _downloadTask = [session downloadTaskWithRequest:request];
    
    [_downloadTask resume];
    
}

#pragma mark URLSessionDownload通过配置文件下载方式

-(void)URLSession:(NSURLSession *)session downloadTask:(nonnull NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{


    NSLog(@"%.2f",(double)totalBytesWritten/totalBytesExpectedToWrite);
    double process =totalBytesWritten/totalBytesExpectedToWrite;
    if (process == 1.00) {
        [MBProgressHUD showSuccess:@"下载成功!"];
    }
    
}

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{

    NSError *saveError;
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString *savePath = [cachePath stringByAppendingPathComponent:@"test1.mp3"];
    NSURL *saveUrl = [NSURL fileURLWithPath:savePath];
   [[NSFileManager defaultManager]copyItemAtURL:location toURL:saveUrl error:&saveError];

    
}



@end
